package com.tornado.community.provider;

import com.tornado.community.mapper.custome.MyUserMapper;
import com.tornado.community.model.User;
import com.tornado.community.service.NotificationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@Component
public class Tools {
    private final MyUserMapper myUserMapper;
    private final NotificationService notificationService;

    @Autowired
    public Tools(MyUserMapper myUserMapper, NotificationService notificationService) {
        this.myUserMapper = myUserMapper;
        this.notificationService = notificationService;
    }

    public User loginCheck(HttpServletRequest request) {
        HttpSession session = request.getSession();
        User user = (User) session.getAttribute("user");
        if (user != null) {
            return user;
        }
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return null;
        }
        for (Cookie cookie : cookies) {
            if (cookie.getName().equals("token")) {
                user = myUserMapper.selectByToken(cookie.getValue());
                if (user != null) {
                    session.setAttribute("user", user);
                    int unreadCount = notificationService.unreadCount(user.getId());
                    session.setAttribute("unreadCount", unreadCount);
                }
                break;
            }
        }
        return user;
    }
}
